package com.example.myframe.base.repo

import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.ActivityUtils
import com.hjq.http.EasyHttp
import com.hjq.http.config.IRequestApi
import com.hjq.http.listener.OnHttpListener
import com.hjq.http.request.GetRequest
import com.a.lib_base.able.IBaseRepo
import com.a.lib_utils.TipUtil
import okhttp3.Call

/**
 * CREATE BY 黄炜强
 * 2022/7/20 17:21
 * Desc:简化了请求的代码
 * */
open class EasyHttpRepoKt : IBaseRepo {


    inline fun <reified T> request(
        getRequest: GetRequest,
        showLoading: Boolean = true,
        crossinline fail: ((Exception) -> Unit),
        crossinline success: ((T) -> Unit)
    ) {
        getRequest.request(object : OnHttpListener<T> {
            override fun onStart(call: Call?) {
                if (showLoading) TipUtil.loadingTip(ActivityUtils.getTopActivity())
            }

            override fun onSucceed(result: T) {
                success.invoke(result)
            }

            override fun onFail(e: Exception) {
                fail.invoke(e)
            }

            override fun onEnd(call: Call?) {
                if (showLoading) TipUtil.dismiss()
            }
        })
    }

    inline fun <reified T> request(
        getRequest: GetRequest,
        crossinline fail: ((Exception) -> Unit),
        crossinline success: ((T) -> Unit)
    ) {
        getRequest.request(object : OnHttpListener<T> {
            override fun onSucceed(result: T) {
                success.invoke(result)
            }

            override fun onFail(e: Exception) {
                fail.invoke(e)
            }
        })
    }

    fun getRequest(owner: LifecycleOwner, api: IRequestApi): GetRequest {
        return EasyHttp.get(owner).api(api)
    }
}